package cn.lrwjz.androidguide.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import cn.lrwjz.androidguide.R;
import cn.lrwjz.androidguide.model.Bill;

public class BillAdapter extends RecyclerView.Adapter<BillAdapter.ViewHolder> {
    private List<Bill> bills;
    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onEditClick(Bill bill);
        void onDeleteClick(Bill bill);
    }

    public BillAdapter(List<Bill> bills, OnItemClickListener listener) {
        this.bills = bills;
        this.listener = listener;
    }

    public void updateData(List<Bill> newBills) {
        this.bills = newBills;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_bill, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Bill bill = bills.get(position);
        holder.tvDescription.setText(bill.getDescription());
        holder.tvAmount.setText(String.format("¥%.2f", bill.getAmount()));
        holder.tvDate.setText(bill.getDate());

        holder.itemView.setOnClickListener(v -> {
            PopupMenu popup = new PopupMenu(v.getContext(), v);
            popup.inflate(R.menu.menu_bill_item);
            popup.setOnMenuItemClickListener(item -> {
                int itemId = item.getItemId();
                if (itemId == R.id.action_edit) {
                    listener.onEditClick(bill);
                    return true;
                } else if (itemId == R.id.action_delete) {
                    listener.onDeleteClick(bill);
                    return true;
                }
                return false;
            });
            popup.show();
        });
    }

    @Override
    public int getItemCount() {
        return bills.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvDescription;
        TextView tvAmount;
        TextView tvDate;

        ViewHolder(View view) {
            super(view);
            tvDescription = view.findViewById(R.id.tv_description);
            tvAmount = view.findViewById(R.id.tv_amount);
            tvDate = view.findViewById(R.id.tv_date);
        }
    }
} 